package com.xuetang9.fujian.donamicproxy.automachine;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Scanner;

/**
 * @author: fujian
 * @description:现在增加对假币的验证
 * @date: 2021/5/1 11:00
 * @version: V1.0
 * @package: com.xuetang9.fujian.donamicproxy.automachine
 **/
@SuppressWarnings("all")
public class VMInvocationHandler implements InvocationHandler {

    private Object target;

    public VMInvocationHandler(Object target) {
        this.target = target;
    }

    public VMInvocationHandler() {
    }

    /*
     * @Description: 方便返回代理对象
     * @param: target
     * @return java.lang.Object
     * @author: fujian
     * @date 2021/5/1 11:11
    */
    public Object bind(Object target){
        this.target = target;
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                new Class<?>[]{IVendingMachine.class, IScanCode.class},
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if ("transaction".equals(method.getName())){
//            在交易之前验证是否是假币
            System.out.println("开始验证投入的是否是假币");
            Thread.sleep(200);
            System.out.println("验证投入的是否是假币结束");
        }
        if ("scan".equals(method.getName())){
            System.out.println("检测到使用扫码工具");
            String code = new Scanner(System.in).nextLine();
            if ("1234".equals(code)){
                return method.invoke(target, args);
            }else {
                return "验证码输入错误";
            }
        }
        // 验证成功继续调用交易的方法
        return method.invoke(target,args);
    }
}
